/*
 * AINearest.cpp
 *
 *  Created on: 2011-5-5
 *      Author: Administrator
 */

#include "AINearest.h"

using namespace Osp::Base::Utility;
using namespace Osp::Base;
using namespace Osp::Base::Collection;

namespace Galaxy {
AINearest::AINearest() {
	__unitsKeeped = (Math::Rand()%5)*5;
}

AINearest::~AINearest() {

}

void AINearest::Play(GalaxyThread* pThread, Player* pMe,
		Osp::Base::Collection::ArrayList* pMyPlanets,
		Osp::Base::Collection::ArrayList* pOtherPlanets,
		Osp::Base::Collection::HashMap* pAccessiblePlanets){
	int myCount = pMyPlanets->GetCount();
	if(myCount == 0){
		return;
	}
	int otherCount = pOtherPlanets->GetCount();
	if(otherCount == 0){
		return;
	}
	bool hasAttack = false;
	for(int i = 0; i < myCount; i++){
		Planet* pPlanet = NULL;
		pPlanet = static_cast<Planet*>(pMyPlanets->GetAt(i));
		if(pPlanet->__soldiersCount >= pPlanet->__maxSoldiers){
			int destPlanetIndex = Math::Rand()%otherCount;
			Planet* pDestPlanet = NULL;
			pDestPlanet = static_cast<Planet*>(pOtherPlanets->GetAt(destPlanetIndex));
			pThread->Attack(pPlanet, pDestPlanet);
			hasAttack = true;
		}
	}
	if(hasAttack){
		return;
	}
	int sourcePlanetIndex = Math::Rand()%myCount;
	Planet* pSourcePlanet = static_cast<Planet*>(pMyPlanets->GetAt(sourcePlanetIndex));
	if(pSourcePlanet->__soldiersCount < this->__unitsKeeped){
		return;
	}
	ArrayList* pAccessible = static_cast<ArrayList*>(pAccessiblePlanets->GetValue(*pSourcePlanet));
	int size = pAccessible->GetCount();
	for(int j = 0; j < size; j++){
		Planet* pPlanet = NULL;
		pPlanet = static_cast<Planet*>(pAccessible->GetAt(j));
		if(pPlanet->__pPlayer == NULL || pPlanet->__pPlayer->__team != pMe->__team){
			pThread->Attack(pSourcePlanet, pPlanet);
			return;
		}
	}
}
}

